<template>
    <div class="my-home-div margin-bottom0">
        <div class="my-home-div-line row">
            <div class="col">
                <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-a-icon_team_teamdata" />
                </svg>
                {{ getuser?.ID === user?.ID ? '我的' : getuser?.name }}数据
                <el-tooltip effect="dark" content="日常练习的数据，不包括比赛数据" placement="top">
                    <span size="default" class="circle">?
                    </span>
                </el-tooltip>
            </div>
        </div>
        <el-scrollbar>
            <div class="m-p-3 m-0 my-info-box">
                <!-- :gutter="12"  -->
                <el-row class="my-info-content-container my-home-div">
                    <el-col :md="6" :sm="12" :xs="6" class="margin-bottom20">
                        <div class="my-info-content cu margin-bottom0 height-100" @click="toAssessment">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-ojSass_personal_pingcetijiaotimushu"></use>
                            </svg>
                            <div class="label">
                                评测题目数
                            </div>
                            <div class="number">
                                <MynumberVue :num="teamdata?.distinctquestionid"></MynumberVue>
                            </div>
                        </div>
                    </el-col>
                    <el-col :md="6" :sm="12" :xs="6" class="margin-bottom20">
                        <div class="my-info-content cu margin-bottom0 height-100" @click="toAssessment">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-ojSass_personal_pingcetijiaocishu"></use>
                            </svg>
                            <div class="label">
                                评测次数
                            </div>
                            <div class="number">
                                <MynumberVue :num="teamdata?.countlength"></MynumberVue>
                            </div>
                        </div>
                    </el-col>
                    <el-col :md="6" :sm="12" :xs="6" class="margin-bottom20">
                        <div class="my-info-content cu margin-bottom0 height-100" @click="toAssessment">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-ojSass_personal_ACtijiaocishu"></use>
                            </svg>
                            <div class="label">
                                全AC题目数
                            </div>
                            <div class="number">
                                <MynumberVue :num="teamdata?.count"></MynumberVue>
                            </div>
                        </div>
                    </el-col>
                    <el-col :md="6" :sm="12" :xs="6" class="margin-bottom20">
                        <div class="my-info-content cu margin-bottom0 height-100" @click="toAssessment">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-ojSass_personal_ACceshidianshu"></use>
                            </svg>
                            <div class="label">
                                AC测试点数
                            </div>
                            <div class="number">
                                <MynumberVue :num="teamdata?.resultdataarrlength"></MynumberVue>
                            </div>
                        </div>
                    </el-col>
                </el-row>

                <!-- 图表 -->
                <div class="my-home-div my-info-chart-container margin-bottom0" v-if="!isshow">
                    <div class="col-6">
                        <vPie :option="acQuestionLabel"></vPie>
                    </div>
                    <div class="col-6">
                        <vBar :option="assessmentTime" :height="'500px'"></vBar>
                    </div>
                    <div class="col-12">
                        <vBar :option="acQuestionDifficult"></vBar>
                    </div>
                </div>
            </div>
        </el-scrollbar>
    </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { asyncselectdistinctuserquestion, asyncteamuserquestion, selectteamrole } from '../../../api';
import MynumberVue from "../../../components/animejs/mynumber.vue";
import { Storekey } from '../../../interface';
import Study from '../../../mysql_interface/studycodemodel';
import vBar from '../../components/vCharts/bar.vue';
import vPie from '../../components/vCharts/pie.vue';
import { DATAdifficulty } from "../../../index/data/data";
const p = defineProps<{ teamid?: number | string, teamdata: any, isshow?: boolean, getuser?: Study.Iuser }>()
const router = useRouter()
const store = useStore(Storekey)
const user = computed(() => {
    return store.state.user
})
const teamId = computed(() => {
    return user.value?.teamid
})
const isAdmin = computed(() => {
    return user.value?.isAdmin
})
const getlabel = computed(() => {
    return store.state.label?.rows || []
})

// watch(() => p.getuser, () => {
//     startchar()
// })

const acQuestionLabel = ref({
    height: 500,
    title: { text: '全AC题目数', left: 'center' },
    tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {c} ({d}%)' },
    legend: {
        orient: 'horizontal', bottom: '60', icon: "roundRect", itemGap: 5,
        type: 'scroll',
        selected: {},
    },
    series: [
        {
            name: "标签",
            type: 'pie',
            radius: '55%',
            center: ['50%', '50%'],
            data: [],
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ]
})
const assessmentTime = ref({
    // height: 350,
    title: { text: "评测时间分布", left: "center", },
    tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" },
        formatter: (params) => {
            let v = params[0] || {}
            let from = Number(v?.name.substring(0, v?.name.length - 1))
            let to = from + 1
            return `<div>
        <div>${from} - ${to}点</div>
        <span >${v?.seriesName}</span>
        <span style="font-weight: bold">${v?.data}</span>
      </div>`;
        },
    },
    grid: { // 直角坐标系内绘图网格
        // show:true, // 是否显示直角坐标系网格。[ default: false ]
        left: "15%", // grid 组件离容器左侧的距离。
        // top: "15%",
        // right:"30px",
        // borderColor:"#c45455",// 网格的边框颜色
        // bottom:"20%"
    },
    dataZoom: [{ type: "inside" }],
    xAxis: {
        type: 'category',
        data: []
    },
    yAxis: { type: 'value', },
    series: [
        {
            name: "提交评测数",
            type: 'bar',
            data: [],
        }
    ],
})
const acQuestionDifficult = ref({
    // height: 300,
    title: { text: "AC题目难度", left: "center", },
    tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" },
    },
    dataZoom: [{ type: "inside" }],
    // legend: {},
    xAxis: { type: 'value', },
    yAxis: { type: 'category', data: [] },
    series: [
        {
            name: "AC题目数",
            type: 'bar',
            data: [],
        }
    ],
    // grid: {
    //     left: '3%',
    //     right: '4%',
    //     // bottom: '3%',
    //     containLabel: true
    // },
})

onMounted(() => {
    startchar()
    getPermissionsCfg()
})

async function startchar() {
    if (p.isshow) return
    if (p.getuser?.ID && p.teamid) {
        try {
            const t = await asyncteamuserquestion({
                teamid: p.teamid,
                todate: new Date,
                formdate: Date.now() - 1000 * 60 * 60 * 24 * 365 * 10,
                userid: p.getuser?.ID
            })

            // 全AC题目标签 - 大于10变其他
            const acQuestionLabelData = []
            const selected = {}
            const limitCount = 20
            t.AClabel.sort((a, b) => b.count - a.count).forEach((e, k) => {
                let labelName = getlabel.value.find(t => t.ID === e.labelid)?.name as string
                // if (k >= 10) {
                //     acQuestionLabelData[10] ? acQuestionLabelData[10].value + e.count : acQuestionLabelData[10] = { name: '其他', value: e.count }
                // } else {
                acQuestionLabelData.push({ name: labelName, value: e.count, })
                // 
                selected[labelName] = k < limitCount
                // }
            })
            acQuestionLabel.value.series[0].data = acQuestionLabelData
            acQuestionLabel.value.legend.selected = selected

            // 评测时间分布
            let assessmentTimeXData = []
            let assessmentTimeYData = []
            Array.from({ length: 24 }).forEach((v, k) => {
                // const date = [k * 4, k * 4 + 1, k * 4 + 2, k * 4 + 3]
                // const z = t.groupkuserquestion.filter(f => date.includes(Number(f.hover))).map(e => e.count).reduce((a = 0, b = 0) => {
                //     return a + b
                // }, 0)
                // assessmentTimeXData.push(date[0] + '-' + (date[3] + 1) + '时')
                // assessmentTimeYData.push(z)
                const z = t.groupkuserquestion.find(f => f.hover == k)
                assessmentTimeXData.push(k + '点')
                if (z) {
                    assessmentTimeYData.push(z.count)
                } else {
                    assessmentTimeYData.push(0)
                }
            })
            assessmentTime.value.xAxis.data = assessmentTimeXData
            assessmentTime.value.series[0].data = assessmentTimeYData

            // Ac题目难度
            const { rows, count } = await asyncselectdistinctuserquestion({
                _order: "questionid",
                userid: p.getuser?.ID,
                resultdata: "AC",
            })
            // DATAdifficulty
            const tempMap = new Map<string, { label: string, count: number }>()
            Object.keys(DATAdifficulty).forEach((v, k) => {
                tempMap.set(v, {
                    label: DATAdifficulty[v],
                    count: 0
                })
            });
            rows.forEach(e => {
                const { question } = e;
                let v = tempMap.get(question.difficulty) || { label: DATAdifficulty[question.difficulty], count: 0 }
                let count = v ? 1 : 0
                v.count += count
            })
            for (const [k, v] of tempMap) {
                acQuestionDifficult.value.yAxis.data.push(v.label)
                acQuestionDifficult.value.series[0].data.push(v.count)
            }
        } catch (e) {
        }
    }
}

function toAssessment() {
    if (isAdmin.value || routerNames.value.find(e => e === '评测')) {
        router.push(`/assessment/?userid=${p.getuser?.ID}`)
    }
    // router.push(`/team/${p.teamid}/teamdata/questiondata?userid=${p.getuser?.ID}`)
}
// 获取权限
const roleName = "学生"
const routerNames = ref<any[]>([])
async function getPermissionsCfg() {
    const { count, rows } = await selectteamrole({
        teamid: p.teamid, name: roleName
    })
    // 可能存在多条
    routerNames.value = rows[0]?.routername || []
}

</script>

<style scoped>
.my-info-box {
    /* max-height: calc(100vh - 64px - 2 * var(--container-margin) - 112px - 24px - 48px); */
}

.my-info-content-container {
    margin-bottom: var(--container-margin);
}

.my-info-content-card {
    width: 25%;
    margin: 0 6px;
}

.my-info-content-container .my-info-content {
    /* height: 228px; */
    /* background-color: #FCFCFC; */
    text-align: center;
    padding-top: 24px;
    transition: all 0.3s;
}

.my-info-content-container .my-info-content:hover {
    /* Depth 16 */
    /* transform: scale(0.98); */
}

.my-info-content-container .my-info-content .icon {
    width: 64px;
    height: 64px;
}

.my-info-content-container .my-info-content .label {
    margin: 14px 0;
    padding: 0 6px;
}

.my-info-content-container .my-info-content .number {
    font-weight: 700;
    font-size: 26px;
    margin-bottom: 10px;
}

.circle {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    height: 16px;
    background-color: #000;
    color: #fff;
    border-radius: 50%;
    width: 16px;
    font-size: 12px;
    font-weight: 400;
    transform: translateY(-1px);
}

.my-info-chart-container {
    padding: 20px 12px;
    display: flex;
    flex-wrap: wrap;
}
</style>